<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-header>
          <el-row>
            <el-col :span="20">
              <span style="fontsize: 12px; color: pink"
                >说明：目前支持学科和关键字条件筛选</span
              >
            </el-col>
            <el-col :span="4" class="headerbutton">
              <el-button
                style="fontsize: 12px"
                type="danger"
                size="small"
                @click="exportExcel"
                >excel导出</el-button
              >
              <el-button
                style="fontsize: 12px"
                type="success"
                icon="el-icon-edit"
                size="small"
                @click="$router.push('/questions/new')"
                >新增试题</el-button
              >
            </el-col>
          </el-row>
          <el-form label-width="80px" :model="searchForm" ref="searchForm">
            <el-row>
              <el-col :span="6">
                <el-form-item label="学科">
                  <el-select
                    v-model="searchForm.subjectID"
                    @change="subjectChange"
                    style="width: 100%"
										placeholder="请选择"
                  >
                    <el-option
                      v-for="item in subjectSimpleList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="二级目录">
                  <el-select
                    v-model="searchForm.catalogID"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in catalogList"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标签">
                  <el-select v-model="searchForm.tags" placeholder="请选择">
                    <el-option
                      v-for="item in tagsList"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="关键字">
                  <el-input
                    placeholder="根据题干搜索"
                    v-model="searchForm.keyword"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="试题类型">
                  <el-select v-model="searchForm.questionType" placeholder="请选择">
                    <el-option
                      v-for="(item, i) of questionType"
                      :key="i"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="难度">
                  <el-select v-model="searchForm.difficulty" placeholder="请选择">
                    <el-option
                      v-for="(item, i) of difficulty"
                      :key="i"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="方向">
                  <el-select v-model="searchForm.direction" placeholder="请选择">
                    <el-option
                      v-for="(item, i) of direction"
                      :key="i"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="录入人">
                  <el-select v-model="searchForm.creatorID" placeholder="请选择">
                    <el-option
                      v-for="item in role"
                      :key="item.id"
                      :label="item.value"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="题目备注">
                  <el-input></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="企业简称">
                  <el-input></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="城市">
                  <el-select
                    v-model="searchForm.province"
                    placeholder="请选择"
                    @change="ProvinceChange"
                    class="province"
                  >
                    <el-option
                      v-for="(item, i) of provincesList"
                      :key="i"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                  <el-select
                    v-model="searchForm.city"
                    placeholder="请选择"
                    class="province"
                  >
                    <el-option
                      v-for="(item, i) of citysList"
                      :key="i"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" class="formbtn">
                <el-form-item>
                  <el-button size="small" @click="clearSearchForm"
                    >清除</el-button
                  >
                  <el-button
                    size="small"
                    @click="searchFormSubmit"
                    type="primary"
                    >搜索</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-header>
        <el-main>
          <el-tabs
            v-model="tabsActiveName"
            type="card"
            @tab-click="handleClick"
          >
            <el-tab-pane label="全部" name="3"></el-tab-pane>
            <el-tab-pane label="待审核" name="0"></el-tab-pane>
            <el-tab-pane label="已审核" name="1"></el-tab-pane>
            <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
          </el-tabs>
          <el-alert
            :title="'数据一共' + total + '条'"
            type="info"
            show-icon
            :closable="false"
						class="info"
          ></el-alert>
          <el-table
            :data="tableData"
            style="width: 100%"
            :header-cell-style="{ background: '#fafafa' }"
          >
            <el-table-column
              label="试题编号"
              prop="number"
              width="115"
            ></el-table-column>
            <el-table-column
              label="学科"
              prop="subject"
              width="80"
            ></el-table-column>
            <el-table-column
              label="目录"
              prop="catalog"
              width="80"
            ></el-table-column>
            <el-table-column label="题型" prop="questionType" width="80">
              <template v-slot="{ row }">
                <span>{{ questionTypeFordata(row.questionType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="题干" prop="question" width="300">
              <template v-slot="{ row }">
                <span v-html="row.question"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="录入时间"
              prop="addDate"
              width="200"
            >
            <template #default="{ row }">
              {{ time(row.addDate) }}
            </template>
            </el-table-column>
            <el-table-column label="难度" prop="difficulty" width="100">
              <template v-slot="{ row }">
                <span>{{ difficultyFordata(row.difficulty) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="录入人"
              prop="creator"
              width="100"
            ></el-table-column>
            <el-table-column label="审核状态" prop="chkState" width="150">
              <template v-slot="{ row }">
                <span>{{ chkStateFordata(row.chkState) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="审核意见"
              prop="chkRemarks"
              width="150"
            ></el-table-column>
            <el-table-column
              label="审核人"
              prop="chkUser"
              width="150"
            ></el-table-column>
            <el-table-column label="发布状态" prop="publishState" width="150">
              <template v-slot="{ row }">
                <span>{{ publishStateFordata(row.publishState) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="250">
              <template v-slot="{ row }">
                <el-button type="text" @click="print(row)">预览</el-button>
                <el-button
                  type="text"
                  @click="choiceCheck(row)"
                  :disabled="row.chkState !== 0"
                  >审核</el-button
                >
                <el-button
                  type="text"
                  @click="edit(row)"
                  :disabled="!!row.publishState"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  @click="choicePublish(row)"
                  :disabled="row.chkState !== 1"
                  >{{ row.publishState ? "下架" : "上架" }}</el-button
                >
                <el-button
                  type="text"
                  @click="delchoice(row)"
                  :disabled="!!row.publishState"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="pagesize"
              layout="  prev, pager, next, sizes,jumper"
              :total="total"
              background
            >
            </el-pagination>
          </div>
          <el-dialog
            title="题目审核"
            :close-on-click-modal="false"
            :visible="dialogFormVisible"
            @close="closeDialog"
            style="width: 800px; margin: 0 auto"
          >
            <el-form
              :model="choiceCheckForm"
              :rules="choiceCheckFormRules"
              ref="choiceCheckForm"
            >
              <el-form-item>
                <el-radio v-model="choiceCheckForm.chkState" :label="1"
                  >通过</el-radio
                >
                <el-radio v-model="choiceCheckForm.chkState" :label="2"
                  >拒绝</el-radio
                >
              </el-form-item>
              <el-form-item prop="chkRemarks">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入审核意见"
                  v-model="choiceCheckForm.chkRemarks"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <div
                  style="
                    display: flex;
                    justifycontent: flex-end;
                    margintop: 30px;
                  "
                >
                  <el-button size="medium" @click="closeDialog">取消</el-button>
                  <el-button
                    size="medium"
                    type="primary"
                    @click="choiceCheckFormSubmit"
                    >确认</el-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </el-dialog>
          <page :show-dialog.sync="showDialog" :UserID="UserID"></page>
        </el-main>
      </el-card>
			<drag></drag>
    </div>
  </div>
</template>

<script>
import {
  choice,
  choiceCheck,
  choicePublish,
  choiceAdd
} from '@/api/hmmm/questions'
import { simple as tagsApi } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import { simple as catalogApi } from '@/api/hmmm/directorys'
import { provinces as provincesApi, citys as citysApi } from '@/api/hmmm/citys'
import {
  questionType,
  difficulty,
  status,
  chkStatus,
  direction
} from '@/api/hmmm/constants'
import baseApi from '@/api/base/baseApi'
import Page from '@/components/questions/page.vue'
import dayjs from 'dayjs'
export default {
  components: {
    Page
  },
  data () {
    return {
      tabsActiveName: '3',
      tableData: [],
      page: 1,
      pagesize: 5,
      questionType,
      difficulty,
      status,
      chkStatus,
      direction,
      role: baseApi.role,
      total: 0,
      dialogFormVisible: false,
      choiceCheckForm: {
        id: '',
        chkState: 1,
        chkRemarks: ''
      },
      choiceCheckFormRules: {
        chkRemarks: [
          { required: true, message: '请输入审核意见', trigger: 'blur' }
        ]
      },
      subjectSimpleList: [],
      searchForm: {
        subjectID: '',
        keyword: '',
        province: '',
        city: '',
        catalogID: '',
        tags: '',
        difficulty: '',
        questionType: '',
        direction: '',
        creatorID: ''
      },
      citysList: [],
      provincesList: [],
      catalogList: [],
      tagsList: [],
      showDialog: false,
      UserID: {},
      tab: '3'
    }
  },
  created () {
    this.getChoiceList()
    this.getsubjectSimpleList()
    this.getCitysList()
    this.getProvinces()
  },
  methods: {
    /**
     * 处理时间
     */
    time (time) {
      return dayjs(time).format('YYYY-MM-DD HH:hh:mm')
    },
    /**
     * 批量excel导出员工信息
     */
    async exportExcel () {
      const headersArr = [
        '试题编号',
        '学科',
        '目录',
        '题型',
        '难度',
        '题干',
        '答案解析',
        '录入人',
        '录入时间'
      ]
      const headersRelations = {
        试题编号: 'number',
        学科: 'subject',
        目录: 'catalog',
        题型: 'questionType',
        题干: 'question',
        难度: 'difficulty',
        答案解析: 'answer',
        录入人: 'creator',
        录入时间: 'addDate'
      }
      const {
        data: { items }
      } = await choice(1, this.total)
      const arr = this.formatDate(items, headersRelations, headersArr)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr,
          data: arr,
          filename: '面试精选题库',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    /**
     * excel导出数据处理
     */
    formatDate (items, headersRelations, headersArr) {
      const result = []
      items.forEach((item) => {
        const tempArr = []
        headersArr.forEach((key) => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (englishKey === 'addDate') {
            value = this.formateTime(value)
          }
          if (englishKey === 'questionType') {
            value = this.questionTypeFordata(value)
          }
          if (englishKey === 'difficulty') {
            value = this.difficultyFordata(value)
          }
          if (['question', 'answer'].includes(englishKey)) {
            value = this.delHtmlTag(value)
          }
          tempArr.push(value)
        })
        result.push(tempArr)
      })
      return result
    },
    // 处理富文本编辑器导出的html标签
    delHtmlTag (str) {
      return str.replace(/<[^>]+>/g, '') // 去掉所有的html标记
    },
    /**
     * 处理时间
     */
    formateTime (time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 预览
    print (id) {
      this.UserID = id
      this.showDialog = true
    },
    /**
     * 学科变化时获取标签和目录
     */
    subjectChange () {
      this.getcatalogList()
      this.getTagsList()
    },
    /**
     *  获取标签列表信息
     */
    async getTagsList () {
      const { data } = await tagsApi({ page: 1, pagesize: 999, subjectID: this.searchForm.subjectID })
      this.searchForm.tags = ''
      this.tagsList = data
    },
    /**
     * 获取目录列表信息
     */
    async getcatalogList () {
      const { data } = await catalogApi({ page: 1, pagesize: 999, subjectID: this.searchForm.subjectID })
      this.searchForm.catalogID = ''
      this.catalogList = data
    },
    ProvinceChange () {
      this.getCitysList()
    },
    /**
     * 获取城市列表信息
     */
    getCitysList () {
      const res = citysApi(this.searchForm.province)
      this.searchForm.city = ''
      this.citysList = res
    },
    /**
     * 获取省份列表信息
     */
    getProvinces () {
      const res = provincesApi()
      this.provincesList = res
    },
    /**
     * 审核状态tab栏切换
     */
    async handleClick (tab) {
      this.tab = tab._props.name
      const obj = { page: 1, pagesize: this.pagesize }
      if (tab._props.name !== '3') {
        obj.chkState = Number(tab._props.name)
      }
      for (const key in this.searchForm) {
        if (this.searchForm[key]) {
          obj[key] = this.searchForm[key]
        }
      }
      const { data } = await choice(obj)
      this.tableData = data.items
      this.total = data.counts
    },
    /**
     * 搜索确认提交按钮
     */
    async searchFormSubmit () {
      const obj = { page: 1, pagesize: this.pagesize }
      for (const key in this.searchForm) {
        if (this.searchForm[key]) {
          obj[key] = this.searchForm[key]
        }
      }
      if (this.tab !== '3') {
        obj.chkState = Number(this.tab)
      }
      const { data } = await choice(obj)
      this.tableData = data.items
      this.total = data.counts
    },
    /**
     * 搜索框重置数据
     */
    clearSearchForm () {
      this.$refs.searchForm.resetFields()
      this.searchForm = {
        subjectID: '',
        keyword: ''
      }
    },
    /**
     * 获取简单学科数据列表
     */
    async getsubjectSimpleList () {
      const { data } = await simple()
      this.subjectSimpleList = data
    },
    /**
     * 移出精选题库
     */
    delchoice (data) {
      this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await choiceAdd({ id: data.id, choiceState: 0 })
          if (this.tableData.length === 1) {
            this.page--
          }
          this.getChoiceList()
        })
        .catch(() => {})
    },
    /**
     * 精选题库上下架
     */
    choicePublish (data) {
      this.$confirm('您确认上架这道题目吗?', '提示', { type: 'warning' })
        .then(async () => {
          const publishState = data.publishState ? 0 : 1
          await choicePublish({ id: data.id, publishState })
          this.getChoiceList()
        })
        .catch(() => {})
    },
    /**
     * 修改审核逻辑
     */
    async edit (row) {
      await choiceCheck({ id: row.id, chkState: 0, chkRemarks: '重新审核' })
      this.$router.push(`/questions/new?id=${row.id}&path=2`)
    },
    /**
     * 审核确认按钮
     */
    choiceCheckFormSubmit () {
      this.$refs.choiceCheckForm.validate(async (flag) => {
        if (!flag) return
        await choiceCheck(this.choiceCheckForm)
        this.$message.success('审核成功')
        this.getChoiceList()
        this.closeDialog()
      })
    },
    /**
     * 审核弹窗关闭
     */
    closeDialog () {
      this.dialogFormVisible = false
      this.$refs.choiceCheckForm.resetFields()
      this.choiceCheckForm = {
        id: '',
        chkState: '1',
        chkRemarks: ''
      }
    },
    /**
     * 	审核
     */
    choiceCheck (data) {
      this.dialogFormVisible = true
      this.choiceCheckForm.id = data.id
    },
    /**
     * 	分页器
     */
    handleSizeChange (val) {
      this.pagesize = val
      this.getChoiceList()
    },
    handleCurrentChange (val) {
      this.page = val
      this.getChoiceList()
    },
    /**
     * 发布状态数据处理
     */
    publishStateFordata (val) {
      let res = ''
      this.status.forEach((k) => {
        if (k.value === val) {
          res = k.label
        }
      })
      return res
    },
    /**
     * 审核状态数据处理
     */
    chkStateFordata (val) {
      let res = ''
      this.chkStatus.forEach((k) => {
        if (k.value === val) {
          res = k.label
        }
      })
      return res
    },
    /**
     * 难度数据处理
     */
    difficultyFordata (val) {
      let res = ''
      this.difficulty.forEach((k) => {
        if (k.value === val) {
          res = k.label
        }
      })
      return res
    },
    /**
     * 题型数据处理
     */
    questionTypeFordata (val) {
      let res = ''
      this.questionType.forEach((k) => {
        if (k.value === val) {
          res = k.label
        }
      })
      return res
    },
    /**
     * 表格初始化数据获取
     */
    async getChoiceList () {
      const obj = { page: this.page, pagesize: this.pagesize }
      for (const key in this.searchForm) {
        if (this.searchForm[key]) {
          obj[key] = this.searchForm[key]
        }
      }
      const { data } = await choice(obj)
      this.tableData = data.items
      this.total = data.counts
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep {
  .el-col {
    height: 32px;
    font-size: 14px;
  }
  .el-row {
    margin-bottom: 20px;
  }
  .formbtn {
    display: flex;
    justify-content: flex-end;
  }
  .el-card__body {
    padding: 20px 0;
  }
  .el-table thead.has-gutter tr {
    background-color: #8df;
  }
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .el-pagination__jump {
    margin-left: 0;
  }
  .el-dialog__body {
    padding-bottom: 5px;
  }
  .el-select.el-select--medium {
    width: 100%;
  }
  .province.el-select.el-select--medium {
    width: 50%;
  }
	.headerbutton{
		display: flex;
		justify-content: flex-end;
	}
	.info{
		margin-bottom: 20px;
	}
}
</style>
